/*!
 * 视频上传模块
 * @author Sherlock 
 * ----------------------------
 * uploaded 上传完成 但未保存属性的函数
 * dosave 保存后的回调函数
 */

require( '../imageUploader/style.less' );
define( [
  'require',
  'jquery',
  'message',
  'qiniu',
  'constants',
  'selector',
  'bootstrap',
  'api'
], function( require, $, ShowTitleMessage ) {
  var returnParam = {};

  var showTime = ShowTitleMessage.showTime;
  var constants = require( 'constants' );
  var apis = require( 'api' ).FILEUPLOAD;
  var me = returnParam.$selector = $( '#video_upload' );
  var videoQiniuUpload = new QiniuJsSDK();

  $( '.video_classify ', me ).selectpicker( {
    size: 8
  } );

  var option_video = {
    runtimes: 'html5,flash,html4', // 上传模式,依次退化
    browse_button: 'video_upload_qiniu', // 上传选择的点选按钮，**必需**
    uptoken_url: apis.GET_VIDEO_UPTOKEN, // Ajax 请求 uptoken 的 Url，**强烈建议设置**（服务端提供）
    get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的 uptoken
    domain: constants.qiniuDomainVideo, // bucket 域名，下载资源时用到，**必需**
    max_file_size: '20mb', // 最大文件体积限制
    flash_swf_url: 'path/of/plupload/Moxie.swf', //引入 flash,相对路径
    max_retries: 0, // 上传失败最大重试次数
    dragdrop: true, // 开启可拖曳上传
    chunk_size: '20mb', // 分块上传时，每块的体积
    auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传,
    multi_selection: 0,
    filters: {
      mime_types: [ {
        title: "Video files",
        extensions: "mp4,flv,f4v,webm,m4v,mov,3gp,3g2,rm,rmvb,wmv,avi,asf,mkv"
      } ]
    },
    init: {
      'FileUploaded': function( up, file, info ) {

        ShowTitleMessage.show( "视频上传成功", showTime );
        // $(".image_upload").parent().find('.add_icon1').attr('style','display:none');
        // $(".image_upload").text('重新上传');
        $( '.btn_upload_video', me ).text( '重新上传' );
        var content = '<video id="example_video_qiniu" class="vjs-default-skin" controls video_id="' + $.parseJSON( info ).video_id + '" video_address="' + jQuery.parseJSON( info ).address1 + '" video_name="' + jQuery.parseJSON( info ).video_name + '">' +
          '<source src="' + $.parseJSON( info ).address + '"  />' +
          '</video>';
        $( '.video_preview', me ).html( content );

        if ( $.isFunction( returnParam.uploaded ) ) {
          returnParam.uploaded.call( this, up, file, info );
        }

        $( '.progress_bar', me ).fadeOut();
      },
      'Error': function( up, err, errTip ) {
        if ( err.code === -600 ) {
          ShowTitleMessage.showWarning( '文件大小超出限制', showTime );
        } else {
          ShowTitleMessage.showWarning( '上传出现问题，请重试', showTime );
        }
        $( '.progress_bar', me ).hide().css( {
          'width': '0%'
        } );
        $( 'input[type="file"]', me ).val( '' );
      },
      'Key': function( up, file ) {
        var name = file.name;
        var ext = name.split( "." );
        var key = constants.userLogin + '_' + ( new Date().getTime() ) + parseInt( Math.random() * 100 ) + '.' + ext[ 1 ];
        return key;
      },
      'BeforeUpload': function( up, file ) {
        $( '.progress_bar', me ).fadeIn().find( '.bar' ).width( 0 );
      },
      'UploadProgress': function( up, file ) {
        $( '.progress_bar .bar', me ).css( {
          'width': file.percent + '%'
        } );
      }
    }
  };
  videoQiniuUpload.uploader( option_video );

  function multipleParam( option ) {
    var param = {
      maxOptions: 5,
      selectedTextFormat: "values",
      multipleSeparator: ',',
      noneSelectedText: '请选择',
      size: 8
    }
    if ( option ) {
      return $.extend( param, option );
    } else {
      return param;
    }
  }
  $( '.more-suffix', me ).popover( {
    placement: 'auto top',
    trigger: 'hover',
    html: true,
    content: '常见在线流媒体格式：mp4，flv，f4v，webm<br/>' + '移动设备格式：m4v，mov，3gp，3g2<br/>' + 'RealPlayer：rm，rmvb<br/>' + '微软格式：wmv，avi，asf<br/>' + 'MPEG视频：mpg，mpeg，mpe，ts<br/>' + 'DV格式：div，dv，divx<br/>' + '其他格式：vob，dat，mkv，swf，lavf，cpk，dirac，ram，qt，fli，flc，mod<br/>'
    //+ '主流音频格式：mp3，acc，ac3，wav，m4a，ogg'
  } );
  /*
   * 文本长度监听
   */
  $( ".txt_right_bor_null", me ).bind( "input propertychange", function() {
    var area = $( this ).val().length;
    $( ".spa_fontcount > span", me ).text( area );
  } );

  $( '#buttonUpload', me ).click( function() {
    var is_show = 0;
    var video_id = $( '#example_video_qiniu', me ).attr( 'video_id' );
    var address1 = $( '#example_video_qiniu', me ).attr( 'video_address' );
    var address = $( '#example_video_qiniu>source', me ).prop( 'src' );

    if ( !address1 ) {
      ShowTitleMessage.showWarning( "请先上传视频", showTime );
      return;
    }
    var title = $( '.txt_right_bor_null', me ).val();
    if ( !title ) {
      ShowTitleMessage.showWarning( "请输入视频标题", showTime );
      return;
    }

    var classify = $( 'select.video_classify', me ).val();

    if ( classify == '未分类' ) {
      ShowTitleMessage.showWarning( "请先选择分类", showTime );
      return;
    }
    //视频标签判断修改 1229 liam start
    var label = '';
    $( '.tag-choosed-video', me ).find( 'button' ).each( function() {
      label += $( this ).text() + ',';
    } )
    label = label.substring( 0, label.length - 1 );
    if ( !label ) {
      ShowTitleMessage.showWarning( "请输入标签", showTime );
      return;
    }
    //视频标签判断修改 1229 liam end
    var synopsis = $.trim( $( '.synopsis', me ).val() );
    if ( !synopsis ) {
      ShowTitleMessage.showWarning( "请输入简介", showTime );
      return;
    }
    var custom = $( '#classify', me ).val();
    if ( $( '#video_share', me ).is( ':checked' ) ) {
      is_show = 1;
    }
    var paramData = {
      video_id: video_id,
      title: title,
      classify: classify,
      label: label,
      synopsis: synopsis,
      address1: address1,
      address: address,
      custom: custom,
      is_show: is_show
    }

    ShowTitleMessage.show( "正在保存" );
    $.post( apis.SAVE_VIDEO, paramData, function( data ) {
      ShowTitleMessage.show( "视频保存成功", showTime );
      var htm = $.parseJSON( data );
      $( '#fm_video_upload', me.modal( 'hide' ) )[ 0 ].reset();

      if ( $.isFunction( returnParam.doSave ) ) {
        returnParam.doSave.call( this, htm, paramData );
      }
    } );
  } );

  // -----------------------------上传视频标签处理-------------------------
  $( '.select-tag-video', me ).selectpicker( multipleParam() ).change( function() {
    var valList = $( this ).val() + "";
    var array = valList.split( ',' );
    var html = '';
    if ( array ) {
      for ( var i = 0; i < array.length; i++ ) {
        html += '<button type="button">' + array[ i ] + '</button>';
      }
    }
    $( '.tag-choosed-video>.system-tag', me ).html( html );
  } );
  $( '.tag-choosed-video>.system-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    var tagArray = new Array();
    $( '.tag-choosed-video>.system-tag>button', me ).each( function() {
      tagArray.push( $( this ).text() );
    } );
    $( '.select-tag-video' ).selectpicker( 'val', tagArray );
  } );
  $( '.tag-choosed-video>.custom-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    $( '.select-tag-video', me ).selectpicker( multipleParam( {
      maxOptions: ( 5 - $( '.tag-choosed-video button', me ).length + $( '.tag-choosed-video>.system-tag>button', me ).length )
    } ) );
  } );
  // 手动加标签
  $( '#inp-addtag-video', me ).keyup( function( e ) {
    e = e || event;
    var regx = /,/;
    var strRep = $.trim( $( this ).val() ).replace( /\s+/g, '' );
    var lastStr = strRep.substr( strRep.length - 1 );
    if ( regx.test( lastStr ) || e.keyCode == 13 ) {
      var tagLen = $( '.tag-choosed-video button', me ).length;
      var flag = true;
      $( '.tag-choosed-video button' ).each( function() {
        if ( strRep == $( this ).text() ) {
          ShowTitleMessage.showWarning( '已存在相同的标签', showTime );
          flag = false;
          return false;
        }
      } );
      if ( tagLen < 5 ) {
        if ( $( '.tag-choosed-video>.custom-tag>button', me ).length == 4 && $( '.tag-choosed-video>.system-tag>button', me ).length == 0 ) {
          ShowTitleMessage.showWarning( '请至少选择一个系统标签', showTime );
          $( this ).val( '' );
          return;
        }
        if ( !flag ) {
          $( this ).val( '' );
          return;
        }
        var html = '';
        var array = strRep.split( ',' );
        for ( var i = 0; i < array.length; i++ ) {
          if ( array[ i ] != '' ) {
            html += '<button type="button">' + array[ i ] + '</button>';
          }
        }
        if ( html != '' ) {
          $( '.tag-choosed-video>.custom-tag', me ).append( html );
          $( '.select-tag-video', me ).selectpicker( multipleParam( {
            maxOptions: ( 5 - tagLen - 1 + $( '.tag-choosed-video>.system-tag>button' ).length )
          } ) );
        } else {
          ShowTitleMessage.showWarning( '空白标签无法添加', showTime );
        }
        $( this ).val( '' );
      } else {
        $( this ).val( '' );
        ShowTitleMessage.showWarning( '系统和自定义标签总共最多五个', showTime );
      }
    }
  } );

  $( '#synopsis', me ).keyup( function() {
    var counter = $( this ).val().length;
    $( this ).parent().find( ".currentLen" ).text( counter );
  } );

  $( '#fm_video_upload', me ).on( 'reset', function() {

    $( '.select-tag-video', this ).selectpicker( 'val', [] );
    $( '.video_classify', this ).selectpicker( 'val', '未选择' );
    $( '.selectpicker', this ).selectpicker( 'refresh' );
    $( '.system-tag, .custom-tag, .video_preview', this ).empty();
    $( '#video_upload_qiniu', this ).text( '上传视频' );
    $( '.spa_fontcount>span', this ).text( 0 );
  } );


  return returnParam;

} );
